package com.css.zfzx.fxpg.modules.vulnerability.area.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.vulnerability.area.repository.FxVulnerabilityAreaNativeRepository;
import com.css.zfzx.fxpg.modules.vulnerability.area.repository.FxVulnerabilityAreaRepository;
import com.css.zfzx.fxpg.modules.vulnerability.area.repository.entity.FxVulnerabilityAreaEntity;
import com.css.zfzx.fxpg.modules.vulnerability.area.service.FxVulnerabilityAreaService;
import com.css.zfzx.fxpg.modules.vulnerability.area.viewobjects.FxVulnerabilityAreaQueryParams;
import com.css.zfzx.fxpg.modules.vulnerability.area.viewobjects.FxVulnerabilityAreaVO;
import com.css.zfzx.fxpg.modules.vulnerability.province.repository.entity.FxVulnerabilityProvinceEntity;
import com.css.zfzx.fxpg.modules.vulnerability.province.service.FxVulnerabilityProvinceService;
import com.css.zfzx.fxpg.modules.vulnerability.province.viewobjects.FxVulnerabilityProvinceQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author leon
 * @date 2020-11-10
 */
@Service
@Slf4j
public class FxVulnerabilityAreaServiceImpl implements FxVulnerabilityAreaService {

    @Autowired
    private FxVulnerabilityAreaRepository fxVulnerabilityAreaRepository;
    @Autowired
    private FxVulnerabilityAreaNativeRepository fxVulnerabilityAreaNativeRepository;
    @Autowired
    private FxVulnerabilityProvinceService fxVulnerabilityProvinceService;

    @Override
    public JSONObject queryFxVulnerabilityAreas(FxVulnerabilityAreaQueryParams queryParams, int curPage, int pageSize) {
        Page<FxVulnerabilityAreaEntity> fxVulnerabilityAreaPage = this.fxVulnerabilityAreaNativeRepository.queryFxVulnerabilityAreas(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxVulnerabilityAreaPage);
        return jsonObject;
    }


    @Override
    public FxVulnerabilityAreaEntity getFxVulnerabilityArea(String id) {
        FxVulnerabilityAreaEntity fxVulnerabilityArea = this.fxVulnerabilityAreaRepository.findById(id).orElse(null);
        return fxVulnerabilityArea;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxVulnerabilityAreaEntity saveFxVulnerabilityArea(FxVulnerabilityAreaEntity fxVulnerabilityArea) {
        String uuid = UUIDGenerator.getUUID();
        fxVulnerabilityArea.setId(uuid);
        fxVulnerabilityArea.setIsValid("1");
        fxVulnerabilityArea.setCreateUser(PlatformSessionUtils.getUserId());
        fxVulnerabilityArea.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxVulnerabilityAreaRepository.save(fxVulnerabilityArea);
        return fxVulnerabilityArea;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxVulnerabilityAreaEntity updateFxVulnerabilityArea(FxVulnerabilityAreaEntity fxVulnerabilityArea) {
        fxVulnerabilityArea.setUpdateUser(PlatformSessionUtils.getUserId());
        fxVulnerabilityArea.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxVulnerabilityArea.getId();
        FxVulnerabilityAreaEntity one = fxVulnerabilityAreaRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxVulnerabilityArea, one);
        this.fxVulnerabilityAreaRepository.save(one);
        return fxVulnerabilityArea;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFxVulnerabilityProvinceByArea(FxVulnerabilityAreaEntity fxVulnerabilityArea) {
        String id = fxVulnerabilityArea.getId();
        FxVulnerabilityAreaEntity oldAreaEntity = getFxVulnerabilityArea(id);
        // 先修改地区数据
        //this.updateFxVulnerabilityArea(fxVulnerabilityArea);
        // 然后修改省份数据
        List<String> filedChanged = whichFiledChanged(fxVulnerabilityArea, oldAreaEntity);
        if (filedChanged.size() > 0) {
            String area = fxVulnerabilityArea.getArea();
            String[] provinces = areaMapProvince(area);
            String structureType = fxVulnerabilityArea.getStructureType();
            String damageDegree = fxVulnerabilityArea.getDamageDegree();
            for (String province : provinces) {
                FxVulnerabilityProvinceQueryParams params = new FxVulnerabilityProvinceQueryParams();
                params.setProvince(province);
                params.setStructureType(structureType);
                params.setDamageDegree(damageDegree);
                List<FxVulnerabilityProvinceEntity> provinceEntities = fxVulnerabilityProvinceService.listFxVulnerabilityProvinces(params);
                for (FxVulnerabilityProvinceEntity provinceEntity : provinceEntities) {
                    updateProvince(filedChanged, provinceEntity, fxVulnerabilityArea);
                }
            }
        }
    }

    private void updateProvince(List<String> filedChanged, FxVulnerabilityProvinceEntity provinceEntity, FxVulnerabilityAreaEntity fxVulnerabilityArea) {
        for (String filed : filedChanged) {
            if ("vi".equals(filed)) {
                provinceEntity.setVulnerabilityVI(fxVulnerabilityArea.getVulnerabilityVI());
            }
            if ("vii".equals(filed)) {
                provinceEntity.setVulnerabilityVII(fxVulnerabilityArea.getVulnerabilityVII());
            }
            if ("viii".equals(filed)) {
                provinceEntity.setVulnerabilityVIII(fxVulnerabilityArea.getVulnerabilityVIII());
            }
            if ("ix".equals(filed)) {
                provinceEntity.setVulnerabilityIX(fxVulnerabilityArea.getVulnerabilityIX());
            }
            if ("x".equals(filed)) {
                provinceEntity.setVulnerabilityX(fxVulnerabilityArea.getVulnerabilityX());
            }
        }
        fxVulnerabilityProvinceService.updateFxVulnerabilityProvince(provinceEntity);
    }

    private List<String> whichFiledChanged(FxVulnerabilityAreaEntity newAreaEntity, FxVulnerabilityAreaEntity oldAreaEntity) {
        ArrayList<String> list = new ArrayList<>();
        // 6度
        if (newAreaEntity.getVulnerabilityVI() != null) {
            if (oldAreaEntity.getVulnerabilityVI() == null) {
                list.add("vi");
            } else {
                String vi = newAreaEntity.getVulnerabilityVI().toString();
                String viOld = oldAreaEntity.getVulnerabilityVI().toString();
                if (!vi.equals(viOld)) {
                    list.add("vi");
                }
            }

        }
        // 7度
        if (newAreaEntity.getVulnerabilityVII() != null) {
            if (oldAreaEntity.getVulnerabilityVII() == null) {
                list.add("vii");
            } else {
                String vii = newAreaEntity.getVulnerabilityVII().toString();
                String viiOld = oldAreaEntity.getVulnerabilityVII().toString();
                if (!vii.equals(viiOld)) {
                    list.add("vii");
                }
            }
        }
        // 8度
        if (newAreaEntity.getVulnerabilityVIII() != null) {
            if (oldAreaEntity.getVulnerabilityVIII() == null) {
                list.add("viii");
            } else {
                String viii = newAreaEntity.getVulnerabilityVIII().toString();
                String viiiOld = oldAreaEntity.getVulnerabilityVIII().toString();
                if (!viii.equals(viiiOld)) {
                    list.add("viii");
                }
            }
        }
        // 9
        if (newAreaEntity.getVulnerabilityIX() != null) {
            if (oldAreaEntity.getVulnerabilityIX() == null){
                list.add("ix");
            }else {
                String ix = newAreaEntity.getVulnerabilityIX().toString();
                String ixOld = oldAreaEntity.getVulnerabilityIX().toString();
                if (!ix.equals(ixOld)) {
                    list.add("ix");
                }
            }
        }
        // 10
        if (newAreaEntity.getVulnerabilityX() != null) {
            if (oldAreaEntity.getVulnerabilityX() == null){
                list.add("x");
            }else {
                String x = newAreaEntity.getVulnerabilityX().toString();
                String xOld = oldAreaEntity.getVulnerabilityX().toString();
                if (!x.equals(xOld)) {
                    list.add("x");
                }
            }
        }
        return list;
    }

    private String[] areaMapProvince(String area) {
        String provinces = "";
        switch (area) {
            case "东北":
                provinces = "黑龙江省,吉林省,辽宁省";
                break;
            case "华东":
                provinces = "上海市,江苏省,浙江省,安徽省,福建省, 江西省,山东省";
                break;
            case "华北":
                provinces = "北京市,天津市,山西省,河北省,内蒙古自治区";
                break;
            case "华中":
                provinces = "河南省,湖北省,湖南省";
                break;
            case "华南":
                provinces = "广东省,广西壮族自治区,海南省";
                break;
            case "西南":
                provinces = "重庆市,四川省,贵州省,云南省,西藏自治区";
                break;
            case "西北":
                provinces = "陕西省,甘肃省,青海省,宁夏回族自治区,新疆维吾尔自治区";
                break;
            default:
                break;
        }
        return provinces.split(",");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxVulnerabilityAreas(List<String> ids) {
        List<FxVulnerabilityAreaEntity> fxVulnerabilityAreaList = this.fxVulnerabilityAreaRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxVulnerabilityAreaList) && fxVulnerabilityAreaList.size() > 0) {
            for (FxVulnerabilityAreaEntity fxVulnerabilityArea : fxVulnerabilityAreaList) {
                this.fxVulnerabilityAreaRepository.delete(fxVulnerabilityArea);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置解析从第1+1+1行开始
            params.setTitleRows(1);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxVulnerabilityAreaVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxVulnerabilityAreaVO.class, params);
            List<FxVulnerabilityAreaVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxVulnerabilityAreaVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxVulnerabilityAreaVO areaVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + areaVO.getRowNum() + "行" + areaVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    @Override
    public void exportExcel(FxVulnerabilityAreaQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxVulnerabilityAreaEntity> areaEntities = fxVulnerabilityAreaNativeRepository.listFxVulnerabilityAreas(queryParams);
            // 深拷贝
            ArrayList<FxVulnerabilityAreaVO> vos = new ArrayList<>();
            for (FxVulnerabilityAreaEntity areaEntity : areaEntities) {
                FxVulnerabilityAreaVO vo = new FxVulnerabilityAreaVO();
                BeanUtils.copyProperties(areaEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "地区易损性信息统计", "地区易损性信息", FxVulnerabilityAreaVO.class, "地区易损性.xlsx", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveExcel(List<FxVulnerabilityAreaVO> list) {
        for (int i = 0; i < list.size(); i++) {
            FxVulnerabilityAreaEntity areaEntity = new FxVulnerabilityAreaEntity();
            FxVulnerabilityAreaVO areaVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(areaVO, areaEntity);
            saveOrUpdate(areaEntity);
        }
    }

    /**
     * 保存或者修改（地区-结构类型-破坏程度-烈度相同的数据只能有一条数据）
     *
     * @param areaEntity
     */
    @Override
    public void saveOrUpdate(FxVulnerabilityAreaEntity areaEntity) {
        FxVulnerabilityAreaQueryParams queryParams = new FxVulnerabilityAreaQueryParams();
        queryParams.setArea(areaEntity.getArea());
        queryParams.setStructureType(areaEntity.getStructureType());
        queryParams.setDamageDegree(areaEntity.getDamageDegree());
        List<FxVulnerabilityAreaEntity> areaEntities = fxVulnerabilityAreaNativeRepository.listFxVulnerabilityAreas(queryParams);
        // 若查到数据为空，则新增
        if (CollectionUtils.isEmpty(areaEntities)) {
            this.saveFxVulnerabilityArea(areaEntity);
        } else {
            if (areaEntities.size() == 1) {
                FxVulnerabilityAreaEntity sourceAreaEntity = areaEntities.get(0);
                BeanUtil.copyPropertiesIgnoreNull(areaEntity, sourceAreaEntity);
                this.updateFxVulnerabilityArea(sourceAreaEntity);
                this.updateFxVulnerabilityProvinceByArea(sourceAreaEntity);
            } else {
                throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
            }
        }
    }

    @Override
    public List<FxVulnerabilityAreaEntity> listFxVulnerabilityAreas(FxVulnerabilityAreaQueryParams queryParams) {
        return fxVulnerabilityAreaNativeRepository.listFxVulnerabilityAreas(queryParams);
    }

    @Override
    public void initialize() {
        List<DictItemEntity> areas = PlatformAPI.getDictAPI().getValidDictItemsByDictCode("area");
        for (DictItemEntity area :
                areas) {
            String areaName = area.getDictItemName();
            // 结构类型
            List<DictItemEntity> structureTypes = PlatformAPI.getDictAPI().getValidDictItemsByDictCode("structureType");
            for (DictItemEntity structureType : structureTypes) {
                String structureName = structureType.getDictItemName();
                // 破坏程度
                List<DictItemEntity> damageDegrees = PlatformAPI.getDictAPI().getValidDictItemsByDictCode("damageDegree");
                for (DictItemEntity damageDegree :
                        damageDegrees) {
                    String damageDegreeName = damageDegree.getDictItemCode();
                    FxVulnerabilityAreaEntity areaEntity = new FxVulnerabilityAreaEntity();
                    areaEntity.setArea(areaName);
                    areaEntity.setStructureType(structureName);
                    areaEntity.setDamageDegree(damageDegreeName);
                    saveFxVulnerabilityArea(areaEntity);
                }
            }
        }

    }

}
